package controller

import (
	"beergo/lib/cache"
	"beergo/lib/tool"
	"encoding/json"
	"errors"
)



func (this *BaseController) GetCache(key string) (string,error) {
	at:=this.CheckAccessToken()
	println(at)
	if cache.Has(at) {
		data := cache.Get(at)
		userData ,ok := data.(map[string]string)
		if ok {
			item,ok:=userData[key]
			if ok {
				return item,nil
			}else {
				return "",nil
			}
		}else {
			return "",errors.New("not found")
		}
	}
	return "",errors.New("内容未找到")
}
func (this *BaseController) SetCache(key string,value interface{}) error {
	at:=this.CheckAccessToken()
	println(at)
	if cache.Has(at) {
		data := cache.Get(at)
		tool.JsonLog(data)
		userData ,ok := data.(map[string]string)
		if ok {
			str,err:= json.Marshal(value)
			if err != nil {
				return err
			}
			userData[key] = string(str)
			cache.Set(at,userData)

		}else {
			return errors.New("")
		}
	}else {
		userData := make(map[string]string)
		str,err:= json.Marshal(value)
		if err != nil {
			return err
		}
		userData[key] = string(str)
		cache.Set(at,userData)
	}
	return nil
}


func (this *BaseController) GetCacheString(key string) (string,error) {
	data ,err := this.GetCache(key)
	if err != nil {
		return "", err
	}
	var wanted string
	wanted = ""
	err=json.Unmarshal([]byte(data),&wanted)
	if err != nil {
		return "", err
	}
	return wanted,nil
}